﻿using System;

namespace p609.datetime
{
    /// <summary>
    /// 时间戳。时间戳是指时间从1970年01月01日00时00分00秒至现在的总秒数
    /// </summary>
    public class Timestamp
    {

        /// <summary>
        /// 基准时间。
        /// DateTime(int year, int month, int day, int hour, int minute, int second) 表示一个特定的日期和时间。它不包含任何关于时区的信息。
        /// </summary>
        private static DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);

        /// <summary>
        /// 转换为时间戳
        /// </summary>
        /// <param name="dateTime">日期时间</param>
        /// <param name="units">时间戳单位。默认是秒</param>
        /// <returns></returns>
        public static long ToTimestamp(DateTime dateTime, TimestampUnits units = TimestampUnits.Second)
        {
            TimeSpan elapsedTime = dateTime - baseTime;
            return units == TimestampUnits.Millisecond ? (long)elapsedTime.TotalMilliseconds  : (long)elapsedTime.TotalSeconds;
        }
        /// <summary>
        /// 转换为日期时间
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns></returns>
        public static DateTime ToDataTime(long timeStamp)
        {
            return Convert.ToString(timeStamp).Length > 12 ? baseTime.AddMilliseconds(timeStamp) : baseTime.AddSeconds(timeStamp);
        }
        /// <summary>
        /// 当前时间的时间戳(UTC时间)
        /// </summary>
        public static long NowTimestamp {  
            get { 
                return ToTimestamp(DateTime.Now, TimestampUnits.Second);
            }
        }

    }
}
